package com.qipay.api.redirect.controller.v1;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qipay.baas.model.Cp;
import com.qipay.baas.model.Order;
import com.qipay.cp.CpService;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.pay.AlipayWapService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.sign.service.SignService;
import com.qipay.sp.SpApiConfigService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/redirect/v1/weixin")
public class WxRedirectController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CpService cpService;

    @Autowired
    SignService signService;

    @Autowired
    AlipayWapService alipayWapService;

    @Autowired
    OrderService orderService;

    @Autowired
    SpConfigService spConfigService;

    @Autowired
    SpApiConfigService spApiConfigService;

    @Autowired
    ObjectMapper objectMapper;

    @Value("${api.response.sign.name}")
    private String sigKey;


    /**
     * 三方的支付宝
     * @param request
     * @param tradeNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/native", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private void otherwap(
            HttpServletRequest request,
            @RequestParam("tradeNo") String tradeNo,
            HttpServletResponse response
    ) throws Exception {
        Assert.notNull(tradeNo, "请输入平台交易流水");
        Order order = orderService.getByTradeNo(tradeNo);
        Assert.notNull(order, "无效订单号");
        Assert.notNull(order.getRemark(), "错误的订单类型");
        Assert.isTrue(order.getState()==1,"无效的订单状态");
        response.sendRedirect(order.getRemark());
    }

    /**
     * 原生的支付宝
     * @param request
     * @param mchId
     * @param tradeNo
     * @param nonceStr
     * @param sign
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wap", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private ModelAndView wap(
            HttpServletRequest request,
            @RequestParam("mch_id") String mchId,
            @RequestParam("trade_no") String tradeNo,
            @RequestParam("nonce_str") String nonceStr,
            @RequestParam("sign") String sign,
            HttpServletResponse response
    ) throws Exception {
        Assert.notNull(mchId, "请输入商户ID");
        Assert.notNull(tradeNo, "请输入平台交易流水");
        Assert.notNull(nonceStr, "请输入随机字符串");
        Assert.notNull(sign, "请输入签名");

        Cp cp = cpService.getOneByAppId(mchId);
        Assert.notNull(cp,"错误的商户ID");

        Map<String, Object> params = new HashMap<>();
        params.put("mch_id",mchId);
        params.put("trade_no",tradeNo);
        params.put("nonce_str",nonceStr);
        params.put("sign",sign);
        String fromSig = params.get(sigKey).toString();
        String mySig = signService.getSign(params, cp.getSecretId(), sigKey);
        Assert.isTrue(StringUtils.equals(fromSig, mySig),"签名错误");

        Order order = orderService.getByTradeNo(tradeNo);
        Assert.notNull(order, "错误的订单信息");
        Assert.isTrue(mchId.equals(order.getCpId().toString()),"输入的商户号与订单信息不一致");
        Assert.isTrue(Objects.equals(order.getState(), OrderStateEnum.NOTPAY.getType()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.ARGUMENT_ERR,"错误的订单信息"));

        Map<String, Object> payInfoMap =  alipayWapService.wapPay(order.getId());
        Assert.notNull(payInfoMap,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的支付宝wap支付失败"));
        Assert.isTrue(payInfoMap.containsKey("result_code"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的支付宝wap支付失败"));
        Assert.isTrue("0".equals(payInfoMap.get("result_code").toString()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的支付宝wap支付失败"));
        Assert.notNull(payInfoMap.get("pay_info"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的支付宝wap支付失败"));

        String payInfo = payInfoMap.get("pay_info").toString();
        ModelAndView modelAndView = new ModelAndView("/pay/wap_script");
        modelAndView.addObject("pay_info", payInfo);
        return modelAndView;
    }

    @RequestMapping(value = "/ykAlipayWap", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private ModelAndView ykAlipayWap(
            HttpServletRequest request,
            @RequestParam("mch_id") String mchId,
            @RequestParam("trade_no") String tradeNo,
            @RequestParam("nonce_str") String nonceStr,
            @RequestParam("sign") String sign,
            HttpServletResponse response
    ) throws Exception {
        Assert.notNull(mchId, "请输入商户ID");
        Assert.notNull(tradeNo, "请输入平台交易流水");
        Assert.notNull(nonceStr, "请输入随机字符串");
        Assert.notNull(sign, "请输入签名");

        Cp cp = cpService.getOneByAppId(mchId);
        Assert.notNull(cp,"错误的商户ID");

        Map<String, Object> params = new HashMap<>();
        params.put("mch_id",mchId);
        params.put("trade_no",tradeNo);
        params.put("nonce_str",nonceStr);
        params.put("sign",sign);
        String fromSig = params.get(sigKey).toString();
        String mySig = signService.getSign(params, cp.getSecretId(), sigKey);
        Assert.isTrue(StringUtils.equals(fromSig, mySig),"签名错误");

        Order order = orderService.getByTradeNo(tradeNo);
        Assert.notNull(order, "错误的订单信息");
        Assert.isTrue(mchId.equals(order.getCpId().toString()),"输入的商户号与订单信息不一致");
        Assert.isTrue(Objects.equals(order.getState(), OrderStateEnum.NOTPAY.getType()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.ARGUMENT_ERR,"错误的订单信息"));

        Map<String, Object> payInfoMap =  alipayWapService.wapPay(order.getId());

        Assert.notNull(payInfoMap,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求赢酷的支付宝wap支付失败"));
        Assert.isTrue(payInfoMap.containsKey("result_code"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求赢酷的支付宝wap支付失败"));
        Assert.isTrue("0".equals(payInfoMap.get("result_code").toString()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求赢酷的支付宝wap支付失败"));
        Assert.notNull(payInfoMap.get("htmlresult"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求赢酷的支付宝wap支付失败"));

        String htmlresult = payInfoMap.get("htmlresult").toString();
        ModelAndView modelAndView = new ModelAndView("/pay/online_bank");
        modelAndView.addObject("result", htmlresult);
        return modelAndView;
    }
}
